/**
 *
 */
package wifiunion.com.notice;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.KeyguardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @ClassName CommonUtils
 * @Description 通用工具类
 * @Version 1.0
 * @Author dqcao
 * @Creation 2016年1月13日 下午5:48:59
 * @Modification 2016年1月13日 下午5:48:59
 */
public class CommonUtils {

    public static MediaPlayer media;

    public static int getPic1Height(Context context, int originW, int originH) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        int picWidth = dm.widthPixels / 2;
        int picHeight = (originH * picWidth) / originW;
        return picHeight;
    }

    public static int getPic1Width(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels / 2;
    }

    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    public static boolean idIsCorrect(String idNumber) {
        String idPattern = "(\\d{14}[(0-9)|X|x])|(\\d{17}[(0-9)|X|x])";

        boolean m = Pattern.matches(idPattern, idNumber);
        return m;
    }

    public static String getHttpUrl(String str) {
        Pattern pattern = Pattern.compile("http://[\\w\\.\\-/:?=]+");
        Matcher matcher = pattern.matcher(str);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            buffer.append(matcher.group());
            buffer.append("\r\n");
        }
        return buffer.toString().trim();
    }

    /**
     * @param time
     * @return String
     * @Name getDateStr
     * @Description yyyy-MM-dd 格式
     * @Author wifiunion
     * @Date 2016年1月19日 下午3:32:40
     */
    public static String getDateStr(Long time) {

        // String str = DateFormat.format(formatStr, time);
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String str = format2.format(new Date(time));
        return str;
    }

    public static String getDateTimeStr(Long time) {
        // String str = DateFormat.format(formatStr, time);

        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String str = format2.format(new Date(time));
        return str;
    }

    public static String getDateTimeSecondStr(Long time) {

        // String str = DateFormat.format(formatStr, time);

        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = format2.format(new Date(time));
        return str;
    }

    /**
     * @param time
     * @return String
     * @Name getHourTimeStr
     * @Description TODO
     * @Author wifiunion
     * @Date 2016年4月26日 下午4:47:20
     */
    public static String getHourTimeSecondStr(Long time) {

        // String str = DateFormat.format(formatStr, time);

        SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");
        String str = format2.format(new Date(time));
        return str;
    }

    public static String getVersionName(Context ctx) {
        String verison = "v ";
        PackageManager manager = ctx.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
            verison = verison + info.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return verison;
    }


    // 开始异或运算
    private static int yihuo(byte[] data) {
        int CRC = 0;
        char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        for (byte b : data) {
            StringBuilder buf = new StringBuilder();
            buf.append(HEX_DIGITS[(b >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[b & 0x0f]);
            // System.out.println("buf=="+buf);
            CRC ^= Integer.parseInt(buf.toString(), 16);
        }
        return CRC;
    }

    // 返回0到256的随机流水号，十六机制
    private static String hexRandom() {
        Random r = new Random();
        int i = r.nextInt(256);
        String hexRandom = Integer.toHexString(i);
        if (hexRandom.length() == 1) {
            hexRandom = "0" + hexRandom;
        }
        return hexRandom;
    }

    /**
     * 是否是大写字母
     *
     * @param s
     * @return
     */
    public static boolean isZiMu(String s) {
        char c = s.charAt(0);
        if ((c >= 'A' && c <= 'Z')) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 过滤特殊字符
     *
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    public static String stringFilter(String str) throws PatternSyntaxException {

        String regEx = "[·/\\:*?<>|\"\n\t]";

        Pattern p = Pattern.compile(regEx);

        Matcher m = p.matcher(str);

        return m.replaceAll("");

    }

    /**
     * 获取设备Id
     *
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {
        TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = TelephonyMgr.getDeviceId();
        return deviceId;
    }


//	public static void finishAllActivity() {
//
//		try {
//			for (Activity activity : ZMKMApplication.getInstance().activityList) {
//
//				if (activity instanceof LoginActivity) {
//				} else {
//					activity.finish();
//				}
//			}
//		} catch (Exception e) {
//
//		}
//	}

    /**
     * 是否在前台 需要权限:android.permission.GET_TASKS
     *
     * @param context
     * @return
     */
    public static boolean isAppOnForeground(Context context) {
        try {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> tasks = am.getRunningTasks(1);
            if (tasks != null && !tasks.isEmpty()) {
                ComponentName topActivity = tasks.get(0).topActivity;
                if (topActivity.getPackageName().equals(context.getPackageName())) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 是否锁屏
     *
     * @param context
     * @return false 没有锁屏 true 锁屏
     */
    public static boolean isNotLockScreen(Context context) {
        try {
            KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode();
            if (flag) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 重设图片
     */
    public static Bitmap resizeBitmap(Bitmap bmp) {

        int bmpszie = 0;
        if (Build.VERSION.SDK_INT < 11) {
            bmpszie = bmp.getRowBytes() * bmp.getHeight();
        } else {
            bmpszie = bmp.getByteCount();
        }

        if (bmpszie / 1024 <= 100) {
            return bmp;
        } else {
            int originWidth = bmp.getWidth();
            int originHeight = bmp.getHeight();

            int goalWidth = (int) (((double) originWidth * 750) / originHeight);

            Bitmap mbitmap = ThumbnailUtils.extractThumbnail(bmp, goalWidth, 750);

            int bitmapCountSize = 0;
            if (Build.VERSION.SDK_INT < 11) {
                bitmapCountSize = mbitmap.getRowBytes() * mbitmap.getHeight();
            } else {
                bitmapCountSize = mbitmap.getByteCount();
            }

            if (bitmapCountSize / 1024 <= 100) {
                return mbitmap;
            }
            ByteArrayOutputStream baos = null;
            try {
                baos = new ByteArrayOutputStream();
                int quality = 100;
                mbitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
                while (baos.toByteArray().length / 1024 > 100) {

                    baos.reset();
                    if (quality > 10) {
                        quality -= 10;
                        mbitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
                    } else {
                        break;
                    }
                }

                ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
                mbitmap = BitmapFactory.decodeStream(isBm, null, null);

            } catch (Exception e) {

            } finally {
                try {
                    baos.flush();
                    baos.close();
                } catch (IOException e) {
                }
            }
            return mbitmap;
        }
    }

    public static String getDecimalFormat(float value) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.#");
        String result = df.format(value);
        if (result.length() == 3) {
            return result;
        } else {
            if (result.length() == 1) {
                return result + ".0";
            }

        }
        return result;
    }

    /**
     * @param context
     * @return boolean
     * @Name isNetWorkAvliable
     * @Description 当前网络是否可以用
     * @Author wifiunion
     * @Date 2016年3月30日 上午11:29:02
     */
    public static boolean isNetWorkAvliable(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean isNumbericOrCharactor(String str) {

        if ((str.charAt(0) >= '0' && str.charAt(0) <= '9') || (str.charAt(0) >= 'a' && str.charAt(0) <= 'z')
                || (str.charAt(0) >= 'A' && str.charAt(0) <= 'Z')) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param urlStr
     * @return String
     * @Name encodeUrl
     * @Description TODO
     * @Author wifiunion
     * @Date 2016年5月4日 上午10:07:33
     */
    public static String encodeUrlParams(String urlStr) {
        urlStr = urlStr.contains("%") ? urlStr.replace("%", "%25") : urlStr;
        urlStr = urlStr.contains("+") ? urlStr.replace("+", "%2B") : urlStr;
        urlStr = urlStr.contains(" ") ? urlStr.replace(" ", "%20") : urlStr;
        urlStr = urlStr.contains("/") ? urlStr.replace("/", "%2F") : urlStr;
        urlStr = urlStr.contains("?") ? urlStr.replace("?", "%3F") : urlStr;
        urlStr = urlStr.contains("#") ? urlStr.replace("#", "%23") : urlStr;
        urlStr = urlStr.contains("&") ? urlStr.replace("&", "%26") : urlStr;
        urlStr = urlStr.contains("=") ? urlStr.replace("=", "%3D") : urlStr;
        return urlStr;
    }


    /**
     * @param DATE1
     * @param DATE2
     * @return 比对时间
     */
    public static int compare_date(String DATE1, String DATE2) {


        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

//    public static boolean exitAuthority(User user, String authorityUuid) {
//        boolean exist = false;
//        List<MenuResponse> menulist = user.getMemberMenu();
//        if (null != menulist && menulist.size() > 0) {
//            for (MenuResponse mp : menulist) {
//                if (null != mp.getChildMenu()) {
//                    for (MenuEntity childMenu : mp.getChildMenu()) {
//                        if (authorityUuid.equals(childMenu.getUuid())) {
//                            exist = true;
//                            break;
//                        }
//                    }
//                }
//
//            }
//
//        }
//        return exist;
//
//    }


    /**
     * 版本号转换
     *
     * @return [版本号]
     */
    public static long loadClientVersion(String versionName) {
        String[] numbers = versionName.split("\\.");

        long ret = 0;

        for (int i = 0; i < numbers.length; i++) {
            ret += Long.parseLong(numbers[i]) << (16 * (3 - i));
        }

        return ret;
    }

    /**
     * 获取软件版本号
     */
    public static String getLocVersionName(Context context) {
        String version = null;

        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return version;
    }


    /**
     * 获取版本号比对是否需要升级
     *
     * @param context
     * @return
     */
    public static boolean HaveNewVersion(Context context, String newversion) {

        if (loadClientVersion(newversion) > loadClientVersion(getCurrentVersion(context))) {
            return true;
        }

        return false;
    }

    /**
     * 对比插件是否需要升级
     *
     * @param cloud
     * @param local
     * @return
     */
    public static boolean PluginVersionComp(String cloud, String local) {
        if (loadClientVersion(cloud) > loadClientVersion(local)) {
            return true;
        }
        return false;

    }


    /**
     * 获取软件版本号
     *
     * @return [版本号]
     */
    public static String getCurrentVersion(Context context) {
        String version = null;

        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return version;
    }

    /**
     * 根据文件路径截取到文件名
     *
     * @param path
     * @return
     */
    public static String getFileName(String path) {
        int separatorIndex = path.lastIndexOf("/");
        return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
    }


    /**
     * 删除文件夹目录下所有文件，不含当前文件夹
     *
     * @param filedir
     */
    public static void deleteAllUnusePackage(String filedir) {
        File file = new File(filedir);
        if (file.exists()) {
            if (file.isDirectory()) {
                for (File subFile : file.listFiles()) {
                    if (subFile.isDirectory()) {

                        for (File fileinSub : subFile.listFiles()) {
                            fileinSub.delete();
                        }
                        subFile.delete();
                    } else {
                        subFile.delete();
                    }
                }
            }
        }
    }




    private static final String MD5_SALT = "rdyOINvHrwVO6HYt";




    public static String encodePwd(String str) {
        String encodePwd = Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
        return encodePwd;
    }

    public static String decodePwd(String base64Token) {
        byte[] m = Base64.decode(base64Token, Base64.DEFAULT);
        String res = new String(m);
        return res;
    }

    public static boolean isNetWorkAviable(Context ctx) {
        try {
            ConnectivityManager cManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cManager.getActiveNetworkInfo();//cManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
            NetworkInfo.State state = networkInfo.getState();

            if (state == NetworkInfo.State.CONNECTED && networkInfo.isConnected()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }


    public static String getHourMinuteSecondStr(long createdTime) {

        SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");
        String str = format2.format(new Date(createdTime));
        return str;
    }


    /**
     * 获取对应包的安装情况 0 未安装 1 已安装可使用  2 已安装待升级
     *
     * @param context
     * @param packageName
     * @return
     */
    public static int getApkIntallStatus(Context context, String packageName, String versionName) {
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> result = pm.getInstalledPackages(0);
        for (PackageInfo pi : result) {
            if (packageName.equals(pi.packageName)) {
                if (PluginVersionComp(versionName, pi.versionName)) {
                    return 2;
                } else {
                    return 1;
                }
            }
        }
        return 0;
    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    public static void install(Context context,File f) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件

            Uri apkUri =
                    FileProvider.getUriForFile(context, "com.wifiunion.intelligencegate.fileprovider", f);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
//            intent.setDataAndType(Uri.fromFile(file),
//                    "application/vnd.android.package-archive");

            intent.setDataAndType(Uri.parse("file://" + f.toString()),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    public static void wakeAndUnlock(Context context) {

        //获取电源管理器对象
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        //获取PowerManager.WakeLock对象，后面的参数|表示同时传入两个值，最后的是调试用的Tag
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");

        //点亮屏幕
        wl.acquire();

        //得到键盘锁管理器对象
        KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");

        //解锁
        kl.disableKeyguard();


    }

}
